<?php
/**
 * File: imageproperty.php.
 * Author: zhouzhe@haibao.com
 * Editor: PhpStorm
 * Date: 16/8/22 下午6:17
 * Brief:
 */
namespace haibao\cms\data;

class ImageProperty extends \haibao\cms\data\BaseMysql{
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ImageProperty');
	}
    
	const IMAGE_CLICK = 1;
	const IMAGE_DOWNLOAD = 2;
	const IMAGE_MARK = 3;
	const IMAGE_PRAISE = 4;
	const IMAGE_SCAN_QRCODE = 5;
	
	public function updateDownNum($imageId){
		$this->dealClickNumData($imageId,self::IMAGE_DOWNLOAD,\haibao\cms\model\data\ImageProperty::HEAT_SCORE_DOWNLOAD);
	}
	
	public function updateMarkNum($imageId){
		$this->dealClickNumData($imageId,self::IMAGE_MARK,\haibao\cms\model\data\ImageProperty::HEAT_SCORE_COLLECTION);
	}

	public function updateClickNum($imageId,$isPc = true,$isFromImageIndex = false){
		$this->dealClickNumData($imageId,self::IMAGE_CLICK,\haibao\cms\model\data\ImageProperty::HEAT_SCORE_VIEW,$isPc,$isFromImageIndex);
	}
	
	public function getPropertyNum($imageId){
		$propertyNums = array('praiseNum'=>0,'commentNum'=>0);
		$sql ='select PraiseCount,CommentNum from ImageProperty where ImageId=%s';
		$result = $this->query($sql,array($imageId));
		while($result->fetch_assoc()){
			$propertyNums['praiseNum'] = $result->getData('PraiseCount');
			$propertyNums['commentNum'] = $result->getData('CommentNum');
		}
		
		return $propertyNums;
	}
	
	public function updatePraiseCount($imageId){
		$this->dealClickNumData($imageId,self::IMAGE_PRAISE,\haibao\cms\model\data\ImageProperty::HEAT_SCORE_PRAISE);
	}
	
	public function updateCommentNum($imageId,$isComment = true,$isQuestion){
        if($isQuestion == \haibao\comment\model\data\CommentContent::CONTENT_IS_COMMENT){
            $field = $isComment ? 'CommentNum' : 'CommentPariseNum';
        }elseif ($isQuestion == \haibao\comment\model\data\CommentContent::CONTENT_IS_QUESTION){
            $field = $isComment ? 'QuestionNum' : 'QuestionPariseNum';
        }
		$heatNum = \haibao\cms\model\data\ImageProperty::HEAT_SCORE_COMMENT;
		$this->beginTranscation();
		try {
			if($isComment){
				$sql = "update ImageProperty set Heat = Heat + ".$heatNum."," . $field . " = " . $field . "+1 where ImageId=%s";
				$result = $this->query($sql, array($imageId));
				if ($result->getAffectRow() == 0) {
					$sql = "insert into ImageProperty(ImageId,Heat,".$field.") value(%s,".$heatNum.",1)";
					$this->query($sql,array($imageId));
				}
			} else {
				$sql = "update ImageProperty set " . $field . " = " . $field . "+1 where ImageId=%s";
				$result = $this->query($sql, array($imageId));
				if ($result->getAffectRow() == 0) {
					$sql = "insert into ImageProperty(ImageId,".$field.") value(%s,1)";
					$this->query($sql,array($imageId));
				}
			}
			
			$this->updateImageIndexTime($imageId);
			
		}catch(\Exception $e){
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation();
	}

	public function subtractCommentNum($imageId,$isComment = true,$isQuestion = \haibao\comment\model\data\CommentContent::CONTENT_IS_COMMENT,$numInfo){
        if($isQuestion == \haibao\comment\model\data\CommentContent::CONTENT_IS_COMMENT){
            $field = $isComment?'CommentNum':'CommentPariseNum';
            $sql = "update ImageProperty set ".$field."=".$field."-1 where ImageId=%s";
        }elseif ($isQuestion == \haibao\comment\model\data\CommentContent::CONTENT_IS_QUESTION){
            $field = $isComment? 'QuestionNum':'QuestionPariseNum';
            if(count($numInfo)>0){
                $sql = "UPDATE ImageProperty SET QuestionNum = QuestionNum -".$numInfo['num'].",QuestionPariseNum = QuestionPariseNum - ".$numInfo['parise']." WHERE ImageId=%s";
            }else{
                $sql = "update ImageProperty set ".$field."=".$field."-1 where ImageId=%s";
            }
        }
	    $result = $this->query($sql, array($imageId));
	    $this->updateImageIndexTime($imageId);
	}
	public function updateScanQrcode($imageId){
		$this->dealClickNumData($imageId,self::IMAGE_SCAN_QRCODE,\haibao\cms\model\data\ImageProperty::HEAT_SCORE_TWO_CODE);
	}
	

	/**
	 * 取最热图片
	 */
	public function getHotImages(){
		$cacheImage = new \haibao\cms\cache\ImageLibrary();
		$imageInfoArr = $cacheImage->getHotImageIds();
		if(empty($imageInfoArr)){
			$sql = "SELECT i.Id,i.Filename from ImageProperty p LEFT JOIN ImageLibrary i on p.ImageId=i.Id where i.IndexTime > '".date("Y-m-d",strtotime("-7 days"))."' ORDER BY p.Heat DESC LIMIT 0,7";
			$result = $this->query($sql);
			$imageInfoArr = array();
			while ($result->fetch_assoc()){
				$imageInfoArr[] = array('Id'=>$result->getData('Id'),'FileName'=>$result->getData('Filename'));
			}
			$cacheImage->setHotImageIds($imageInfoArr);
		} else {
			$imageInfoArr = json_decode($imageInfoArr,true);
		}
	
		return $imageInfoArr;
	}
	
	public function getRelateList($imageId,$limit = 3){
		$articleInfoArr = $this->getArticleByImageId($imageId);
		$imageCollectiveInfoArr = $this->getImageCollectiveByImageId($imageId);
			
		$infoArr = array_merge($articleInfoArr,$imageCollectiveInfoArr);
		$objectList = array_slice($infoArr, 0,3);
		
		return $objectList;
	}
	
	/**
	 * 通过图片ID得相关的文章（发布时间倒序）
	 * @param int $imageId
	 * @param int $limit
	 * @return multitype:multitype:NULL Ambigous <NULL, \DateTime>
	 */
	private function getArticleByImageId($imageId,$limit = 3){
		$sql = "SELECT a.Title,a.PublishId,UNIX_TIMESTAMP(a.PublishTime) as PublishTime from Article a LEFT JOIN ArticleImage i on i.ArticleId=a.Id where a.Published=1 and a.`Status`=0 and a.`Level`>0 and i.ImageId=".$imageId." ORDER BY a.PublishTime DESC LIMIT 0,".$limit;
		$result = $this->query($sql);
		$articleInfoArr = array();
		while ($result->fetch_assoc()){
			$articleInfoArr[] = array('Title'=>$result->getData('Title'),'PublishId'=>$result->getData('PublishId'),'ObjectType'=>0);
		}
		
		return $articleInfoArr;
	}
	
	/**
	 * 通过图片ID得相关的图集（发布时间倒序）
	 * @param int $imageId
	 * @param int $limit
	 * @return multitype:multitype:NULL Ambigous <NULL, \DateTime>
	 */
	private function getImageCollectiveByImageId($imageId,$limit = 3){
		$sql = "SELECT a.Title,a.Id,UNIX_TIMESTAMP(a.PublishTime) as PublishTime from ImageCollective a LEFT JOIN ImageCollectivePic i on i.ImageCollectiveId=a.Id where a.Published=1 and a.`Status`=1 and a.`Level`>0 and i.ImageId=".$imageId." ORDER BY a.PublishTime DESC LIMIT 0,".$limit;
		$result = $this->query($sql);
		$imageCollectiveInfoArr = array();
		while ($result->fetch_assoc()){
			$imageCollectiveInfoArr[$result->getData('PublishTime')] = array('Title'=>$result->getData('Title'),'PublishId'=>$result->getData('Id'),'ObjectType'=>1);
		}
	
		return $imageCollectiveInfoArr;
	}
	
	private function updateImageIndexTime($imageId){
		$data = new \haibao\cms\data\ImageLibrary();
		$data->updateImageIndexTime($imageId);
	}
	
	public function dealClickNumData($imageId,$type,$heatNum,$isPc = true,$isFromImageIndex = false){
	    $dataList = array();
	    $dataList['imageId'] = $imageId;
	    $dataList['type'] = $type;
	    $dataList['time'] = time();
	    if(!$isPc){
	        $dataList['wap'] = 1;
	    }
	    if(self::IMAGE_CLICK == $type && $isFromImageIndex){
            $dataList['isIndex'] = 1;
	    }
	    $cacheData = new \haibao\cms\cache\ImageLibrary();
	    $cacheData->setImageProperty($dataList);
	}
	
	public function insertImageHeat($imgIds,$imgLevel){
	    $str = preg_replace('/(\d+)/', '%s', implode(',', $imgIds));
	    $sql = "SELECT ImageId FROM `ImageProperty` WHERE ImageId IN (".$str.")";
	    $result = $this->query($sql,$imgIds);
	    $hasImgIds = array();
	    while ($row = $result->fetch_assoc()){
	        array_push($hasImgIds, $row['ImageId']);
	    }
	    if($hasImgIds){
	        $imgIds = array_diff($imgIds,$hasImgIds);
	    }
	    $dataImgArr = array();
	    foreach ($imgIds as $k=>$v){
            $imgHeat = 0;
            switch ($imgLevel){
                case \haibao\cms\model\data\ImageLibrary::LEVEL_EXQUISITE:
                    if($k == 0){
                        $imgHeat = 5000;
                    } elseif($k == 1) {
                        $imgHeat = rand(4000,4500);
                    }elseif($k == 2) {
                        $imgHeat = rand(3500,4000);
                    } else {
                        $imgHeat = rand(500,2000);
                    }
                    break;
                case \haibao\cms\model\data\ImageLibrary::LEVEL_ORDINARY:
                    if($k == 0){
                        $imgHeat = 3000;
                    } elseif($k == 1) {
                        $imgHeat = rand(2000,2500);
                    }elseif($k == 2) {
                        $imgHeat = rand(1500,2000);
                    } else {
                        $imgHeat = rand(500,1000);
                    }
                    break;
            }
	        $dataImg = new \haibao\cms\model\data\ImageProperty();
	        $dataImg->ImageId = $v;
	        $dataImg->ClickCount = 0;
	        $dataImg->PraiseCount = 0;
	        $dataImg->Heat = $imgHeat;
	        $dataImg->CommentNum = 0;
	        $dataImg->CommentPariseNum = 0;
	        $dataImg->MobileClickNum = 0;
	        $dataImg->PcClickNum = 0;
	        $dataImg->DownNum = 0;
	        $dataImg->MarkNum = 0;
	        $dataImg->IndexPcClickNum = 0;
	        $dataImg->IndexMobileClickNum = 0;
	        $dataImg->QuestionNum = 0;
	        $dataImg->QuestionPariseNum = 0;
	        array_push($dataImgArr, $dataImg);
	    }
	    $this->addAll($dataImgArr);
	}
}